<template>
	<view class="address-edit">
		<!-- 顶部提示 -->
		<view class="tips">
			<view class="icon-wrap">
				<u-icon name="info-circle" size="28" color="#018d71"></u-icon>
			</view>
			<text>请填写准确的收货地址，以确保商品顺利送达</text>
		</view>
		
		<view class="form">
			<!-- 联系人 -->
			<view class="form-item">
				<view class="label">
					<text class="required">*</text>
					<text>联系人</text>
				</view>
				<input 
					type="text" 
					v-model="form.name" 
					placeholder="请输入姓名"
					placeholder-class="placeholder"
				/>
			</view>
			
			<!-- 手机号 -->
			<view class="form-item">
				<view class="label">
					<text class="required">*</text>
					<text>手机号</text>
				</view>
				<input 
					type="number" 
					v-model="form.mobile" 
					placeholder="请输入手机号" 
					maxlength="11"
					placeholder-class="placeholder"
				/>
			</view>
			
			<!-- 地址选择 -->
			<view class="form-item">
				<view class="label">
					<text class="required">*</text>
					<text>选择地址</text>
				</view>
				<view class="address-select" @tap="chooseLocation">
					<text class="address" v-if="form.location">{{form.location}}</text>
					<text class="placeholder" v-else>点击选择收货地址</text>
					<view class="map-icon">
						<u-icon name="map-fill" size="36" color="#018d71"></u-icon>
					</view>
				</view>
			</view>
			
			<!-- 详细地址 -->
			<view class="form-item">
				<view class="label">
					<text class="required">*</text>
					<text>门牌号</text>
				</view>
				<input 
					type="text"
					v-model="form.house_number"
					placeholder="请输入楼号门牌号，例如:8号楼801室"
					placeholder-class="placeholder"
				/>
			</view>
			
			<!-- 设为默认 -->
			<view class="form-item switch">
				<text class="label">设为默认</text>
				<view class="switch-box">
					<switch :checked="form.is_default" @change="onSwitchChange" color="#018d71"/>
					<text class="desc">设为默认收货地址</text>
				</view>
			</view>
		</view>
		
		<!-- 底部按钮 -->
		<view class="footer">
			<view class="save-btn" @tap="saveAddress">
				<text>保存地址</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					name: '',
					mobile: '',
					location: '', // 地图选择的地址
					house_number: '', // 门牌号
					latitude: null,
					longitude: null,
					is_default: false
				},
				id: '', // 编辑时的地址ID
				// 店铺位置
				shopLocation: {
					latitude: 23.12908,  // 店铺纬度
					longitude: 113.26436 // 店铺经度
				}
			}
		},
		onLoad(e) {
			if(e.id) {
				this.id = e.id
				this.getAddressDetail()
			}
			this.getConfig();
		},
		methods: {
			// 获取地址详情
			getAddressDetail() {
				vk.callFunction({
					url: 'client/address/kh/address',
					data: {
						id: this.id
					},
					success: (data) => {
						if(data.item) {
							this.form = data.item
						}
					}
				})
			},
			// 切换默认状态
			onSwitchChange(e) {
				this.form.is_default = e.detail.value
			},
			// 计算两点之间的距离(单位:米)
			calculateDistance(lat1, lon1, lat2, lon2) {
				const R = 6371000 // 地球半径(米)
				const dLat = this.deg2rad(lat2 - lat1)
				const dLon = this.deg2rad(lon2 - lon1)
				const a = 
					Math.sin(dLat/2) * Math.sin(dLat/2) +
					Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * 
					Math.sin(dLon/2) * Math.sin(dLon/2)
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
				return R * c
			},
			// 角度转弧度
			deg2rad(deg) {
				return deg * (Math.PI/180)
			},
			// 检查配送范围
			checkDeliveryRange(latitude, longitude) {
				const distance = this.calculateDistance(
					latitude,
					longitude,
					this.shopLocation.latitude,
					this.shopLocation.longitude
				)
				return {
					inRange: distance <= this.configDistance * 1000, // 3公里范围
					distance: Math.round(distance)
				}
			},
			getConfig() {
				vk.callFunction({
					url: 'client/system/pub/config',	
					success: (data) => {
						if(data.item) {
							this.shopLocation = data.item.shopLocation
							this.configDistance = data.item.deliver_distance
						}
					}
				})
			},
			// 选择地址
			chooseLocation() {
				uni.chooseLocation({
					success: (res) => {
						// 检查配送范围
						const { inRange, distance } = this.checkDeliveryRange(res.latitude, res.longitude)
						
						if (!inRange) {
							uni.showModal({
								title: '超出配送范围',
								content: `该地址距离门店${(distance/1000).toFixed(1)}公里，超出配送范围(${this.configDistance}公里)`,
								showCancel: false
							})
							return
						}
						
						// 保存地址信息
						this.form.location = res.address
						this.form.latitude = res.latitude
						this.form.longitude = res.longitude
					},
					fail: (err) => {
						console.log(err);
						if(err.errMsg.indexOf('auth deny') !== -1) {
							uni.showModal({
								title: '提示',
								content: '请在系统设置中打开定位权限',
								showCancel: false
							})
						} else {
							uni.showToast({
								title: '选择地址失败',
								icon: 'none'
							})
						}
						
					}
				})
			},
			// 验证表单
			validateForm() {
				if(!this.form.name) {
					uni.showToast({
						title: '请输入联系人',
						icon: 'none'
					})
					return false
				}
				if(!this.form.mobile) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					})
					return false
				}
				if(!/^1\d{10}$/.test(this.form.mobile)) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					})
					return false
				}
				if(!this.form.location) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					})
					return false
				}
				if(!this.form.house_number) {
					uni.showToast({
						title: '请输入门牌号',
						icon: 'none'
					})
					return false
				}
				return true
			},
			// 保存地址
			saveAddress() {
				if(!this.validateForm()) return
				
				// 再次检查配送范围(防止数据被篡改)
				const { inRange, distance } = this.checkDeliveryRange(
					this.form.latitude,
					this.form.longitude
				)
				
				if (!inRange) {
					uni.showModal({
						title: '超出配送范围',
						content: `该地址距离门店${(distance/1000).toFixed(1)}公里，超出配送范围(3公里)`,
						showCancel: false
					})
					return
				}
				
				const data = {
					...this.form,
					uid: vk.getVuex('$user.userInfo._id')
				}
				
				if(this.id) {
					data.id = this.id
				}
				
				vk.callFunction({
					url: this.id ? 'client/address/kh/update' : 'client/address/kh/add',
					data,
					success: () => {
						uni.showToast({
							title: '保存成功'
						})
						// 刷新上一页的地址列表
						let pages = getCurrentPages()
						let prevPage = pages[pages.length - 2]
						if(prevPage && prevPage.$vm.getAddressList) {
							prevPage.$vm.getAddressList()
						}
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.address-edit {
	min-height: 100vh;
	background-color: #f8f8f8;
	padding-bottom: 180rpx;
	
	.tips {
		display: flex;
		align-items: center;
		padding: 24rpx 30rpx;
		background-color: rgba(1,141,113,0.1);
		margin-bottom: 20rpx;
		
		.icon-wrap {
			width: 44rpx;
			height: 44rpx;
			background: rgba(255,255,255,0.8);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		text {
			flex: 1;
			font-size: 24rpx;
			color: #018d71;
			margin-left: 16rpx;
			line-height: 1.5;
		}
	}
	
	.form {
		background-color: #fff;
		margin: 0 20rpx;
		padding: 0 30rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.05);
		
		.form-item {
			display: flex;
			align-items: flex-start;
			padding: 30rpx 0;
			border-bottom: 1rpx solid #f5f5f5;
			
			.label {
				width: 160rpx;
				font-size: 30rpx;
				color: #666;
				padding-top: 6rpx;
				display: flex;
				
				.required {
					color: #ff5722;
					margin-right: 6rpx;
				}
			}
			
			input {
				flex: 1;
				font-size: 28rpx;
				color: #333;
				height: 80rpx;
				line-height: 80rpx;
				background-color: #f8f8f8;
				border-radius: 12rpx;
				padding: 0 24rpx;
			}
			
			.address-select {
				flex: 1;
				display: flex;
				align-items: center;
				background-color: #f8f8f8;
				border-radius: 12rpx;
				padding: 20rpx 24rpx;
				min-height: 80rpx;
				
				.address {
					flex: 1;
					font-size: 28rpx;
					color: #333;
					margin-right: 20rpx;
				}
				
				.placeholder {
					flex: 1;
					font-size: 28rpx;
					color: #999;
					margin-right: 20rpx;
				}
				
				.map-icon {
					width: 64rpx;
					height: 64rpx;
					background: rgba(1,141,113,0.1);
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
			
			&.switch {
				align-items: center;
				
				.label {
					padding-top: 0;
				}
				
				.switch-box {
					flex: 1;
					display: flex;
					align-items: center;
					
					.desc {
						font-size: 26rpx;
						color: #666;
						margin-left: 20rpx;
					}
				}
			}
			
			&:last-child {
				border-bottom: none;
			}
		}
	}
	
	.placeholder {
		color: #999;
		font-size: 28rpx;
	}
	
	.footer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 30rpx 40rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 20rpx rgba(0,0,0,0.08);
		
		.save-btn {
			height: 88rpx;
			text-align: center;
			background: linear-gradient(135deg, #02a584 0%, #018d71 100%);
			color: #fff;
			border-radius: 44rpx;
			font-size: 30rpx;
			box-shadow: 0 8rpx 16rpx rgba(1,141,113,0.2);
			transition: transform 0.2s;
			display: flex;
			align-items: center;
			justify-content: center;
			
			text {
				font-weight: 500;
				letter-spacing: 2rpx;
			}
			
			&:active {
				transform: translateY(2rpx);
			}
		}
	}
}
</style>
